<?php
/**
 * 周舟 hzboye010@163.com
 * addby sublime snippets
 */
namespace Common\Api;
use Common\Api\Api;
use Common\Model\ScoreGoodsModel;
use Admin\Api\MemberApi;
use Common\Api\ExchangeLogApi;
use Shop\Api\RedEnvelopeApi;
use Shop\Api\CouponApi;
use Admin\Api\AddressApi;
use Tool\Api\AreaApi;
use Tool\Api\CityApi;
use Tool\Api\ProvinceApi;
use Ucenter\Model\UserLogModel;
use Shop\Api\WalletApi;

class ScoreGoodsApi extends Api{
  //萌币商品类型 优惠券数额写在前面+>intval
  public static $types = array(
    '1'=>'实物',
    '2'=>'红包',
    '3'=>'优惠券',
    '0'=>'其他',
  );
  const QUERY    = "Common/ScoreGoods/myFind";
  const PAGE     = "Common/ScoreGoods/page";
  const ORPAGE   = "Common/ScoreGoods/query";
  const DELETE   = "Common/ScoreGoods/delete";
  const ADD      = "Common/ScoreGoods/add";
  const SAVE     = "Common/ScoreGoods/save";
  const DETAIL   = "Common/ScoreGoods/detail";
  const GET_INFO = "Common/ScoreGoods/getInfo";
  const CHANGE   = "Common/ScoreGoods/shelf";
  const GET_PAY_URL = "Common/ScoreGoods/getPayUrl";
  const EXCHANGE = "Common/ScoreGoods/exchange";
  const GET_TPL_NAME = "Common/ScoreGoods/getTplName";
  const GET_TPL_INFO = "Common/ScoreGoods/getTplInfo";

  public function getTplName($type,$tplid){
    $type  = intval($type);
    $tplid = intval($tplid);
    $table = '';
    if($type == 2){
      $table = 'itboye_red_envelope_tpl';
    }elseif($type==3){
      $table = 'itboye_coupon_tpl';
    }
    if($table){
      $model = M();
      $sql = 'select dt.name from common_datatree as dt left join '.$table.' as tpl on tpl.dtree_type = dt.id where tpl.id='.$tplid;
      // return $this->apiReturnErr($sql);
      $r = $model->query($sql);
     if(false === $r) return $this->apiReturnErr($model->getDbError());
     if(empty($r[0])) return $this->apiReturnErr('模板已失效'.$tplid);
     return $this->apiReturnSuc($r[0]['name']);
    }else{
      return $this->apiReturnSuc('');
    }
  }

  public function getTplInfo($type,$tplid){
    $type  = intval($type);
    $tplid = intval($tplid);
    $table = '';
    if($type == 2){
      $table = 'itboye_red_envelope_tpl';
    }elseif($type==3){
      $table = 'itboye_coupon_tpl';
    }
    if($table){
      $model = M();
      $sql = 'select dt.name,tpl.* from common_datatree as dt left join '.$table.' as tpl on tpl.dtree_type = dt.id where tpl.id='.$tplid;
      // return $this->apiReturnErr($sql);
      $r = $model->query($sql);
     if(false === $r) return $this->apiReturnErr($model->getDbError());
     if(empty($r)) return $this->aiReturnErr('模板已失效'.$tpl_id);
     return $this->apiReturnSuc($r[0]);
    }else{
      return $this->apiReturnErr('类型错误：'.$type);
    }
  }

  public function myFind($where=null,$start,$length,$order="create_time desc"){
    // $order = '';
    // return $this -> apiReturnSuc($order);
    if(empty($where)) $where = array('onshelf'=>1,'status'=>0);//,'status'=>1
    else{
      $where['onshelf'] = 1;
      $where['status']  = 0;
    }
    $r  = $this-> model //->cache(true)
      // ->alias('g')
      // ->relation(true)
      // ->join(C('DB_PREFIX').'user_picture p ON g.main_img = p.id')
      // ->field('g.*,p.path')
      ->where($where)->limit($start,$length)->order($order)->select();
    if(false === $r) return $this->apiReturnErr($this->model->getDbError());
    $count = $this->model->where($where)->order($order)->count();
    if(false === $count) return $this->apiReturnErr($this->model->getDbError());
    // dump($r);
    // dump($this->getLastSql());exit;
    return $this -> apiReturnSuc(array('list'=>$r,'count'=>$count));
  }

  public function shelf($gid,$onshelf){
    if($r = $this->model->where(array('id'=>$gid))->setField('onshelf',$onshelf))
      return $this->apiReturnSuc($r);//->cache(true)
    else
      return $this->apiReturnErr($r);
  }

  public function page($where,$page){
    // $where = array('game_id'=>$gid);
    $page = array('curpage'=>$page,'size'=>10);

    $r = $this -> model ->where($where);//->cache(true)

    $list = $r -> page($page['curpage'].','.$page['size']) -> select();
    if ($list === false) {
      $error = $this -> model -> getDbError();
      return $this -> apiReturnErr($error);
    }
    $count = $r -> count();
    $Page = new \Think\Page($count, $page['size']);
    //分页跳转的时候保证查询条件
    if ($params !== false) {
      foreach ($params as $key => $val) {
        $Page -> parameter[$key] = urlencode($val);
      }
    }
      $show = $Page -> show();
      return $this -> apiReturnSuc(array("show" => $show, "list" => $list));
  }
  //萌币商品兑换
  public function exchange($uid,$psw,$pid){
    $r = apiCall(MemberApi::GET_INFO,array(array('uid'=>$uid)));
    if(!$r['status'])     return $this->apiReturnErr($r['info']);
    if(empty($r['info'])) return $this->apiReturnErr('uid错误');
    $member = $r['info'];

    $r = $this->getInfo(array('id'=>$pid));
    if(!$r['status'])     return $this->apiReturnErr($r['info']);
    if(empty($r['info'])) return $this->apiReturnErr('pid错误');
    $sgood  = $r['info'];

    $count  = intval($sgood['count']);
    if($count === 0)      return $this->apiReturnErr('该商品已兑完');
    $score  = intval($sgood['score']);
    if(1>$score)          return $this->apiReturnErr('兑换萌币小于1,请联系客服人员修改');
    $mscore = intval($member['score']);
    if($mscore < $score)  return $this->apiReturnErr('萌币不足');
    $price  = floatval($sgood['price']);
    if($price < 0)        return $this->apiReturnErr('兑换价小于0,请联系客服人员修改');
    $type   = intval($sgood['type']);
    $tpl_id = intval($sgood['tpl_id']);
    //查询tpl_name
    $tpl_info = array();
    $tpl_name = $tpl_id ? $tpl_id.'元包邮':'免邮';
    if(in_array($type,array(2,3))){
      $post_price = 0;
      $r = $this->getTplInfo($type,$tpl_id);
      if(!$r['status'])     return $this->apiReturnErr($r['info']);
      if(empty($r['info'])) return $this->apiReturnErr('模板错误：'.$type.'-'.$tpl_id);
      $tpl_info = $r['info'];
      $tpl_name = $tpl_info['name'];
    }else{
      $post_price = $tpl_id;
    }
    //查询限购
    $buy_limit = intval($sgood['buy_limit']);
    if($buy_limit){
      $r = apiCall(ExchangeLogApi::COUNT,array(array('uid'=>$uid,'pid'=>$pid)));
      if(!$r['status']) return $this->apiReturnErr($r['info']);
      $buy_count = intval($r['info']);
      if($buy_count && $buy_count>=$buy_limit){
        return $this->apiReturnErr('超出限购,您已兑换'.$buy_count.'件');
      }
    }

    $this->model->startTrans();
    //减少萌币 - 上面以判断
    $r = apiCall(MemberApi::SET_DEC,array(array('uid'=>$uid),'score',$score));
    if(!$r['status']){
      $this->model->rollback();
      return $this->apiReturnErr($r['info']);
    }
    //添加萌币减少记录
    $r = apiCall(MemberApi::SCORE_LOG,array($uid,-$score,UserLogModel::EXCHANGE_SGOODS));
    if(!$r['status']){
      $this->model->rollback();
      return $this->apiReturnErr($r['info']);
    }
    $exStatus = (($price+$post_price) == 0)?0:-1;
    //-1代付款 0待发货 1已发货
    // dump($exStatus);exit;
    $member['score'] = $mscore - $score;
    //增加兑换记录
    $map = array(
        'pid'       =>$pid
        ,'pname'    =>$sgood['name']
        ,'price'    =>($price+$post_price)
        ,'score'    =>$score
        ,'uid'      =>$uid
        ,'type'     =>$type
        ,'tpl_id'   =>$tpl_id
        ,'tpl_name' =>$tpl_name
        ,'main_img' =>$sgood['main_img']
        ,'brand'    =>$sgood['brand']
        // ,'pay_code'        =>$code
        ,'exchange_status' =>$exStatus
    );
    $r = apiCall(ExchangeLogApi::ADD,array($map));
    if(!$r['status']){
      $this->model->rollback();
      return $this->apiReturnErr($r['info']);
    }
    if(empty($r['info'])){
      $this->model->rollback();
      return $this->apiReturnErr('兑换失败:LOG_ERROR');
    }
    $id = intval($r['info']);
    if($exStatus === 0){
      $msg = '支付成功，请耐心等待工作人员发货！';
      if($type === 2){
        //发放红包 + 推送
        $r = apiCall(RedEnvelopeApi::SEND_TO_USER,array($uid,$tpl_id,'红包[萌币兑换]',0,0,true));
        if(!$r['status']){
          $this->model->rollback();
          return $this->apiReturnErr($r['info']);
        }
        //修改兑换状态
        $r = apiCall(ExchangeLogApi::SAVE,array(array('id'=>$id),array('exchange_status'=>1)));
        if(!$r['status']){
          $this->model->rollback();
          return $this->apiReturnErr($r['info']);
        }
        $msg = '红包发放成功，请前往百宝箱查看！';
      }else if($type === 3){
        //发放优惠券 + 推送
        $r = apiCall(CouponApi::SEND_TO_USER,array($uid,$tpl_id,'优惠券[萌币兑换]',0,0,true));
        if(!$r['status']){
          $this->model->rollback();
          return $this->apiReturnErr($r['info']);
        }
        //修改兑换状态
        $r = apiCall(ExchangeLogApi::SAVE,array(array('id'=>$id),array('exchange_status'=>1)));
        if(!$r['status']){
          $this->model->rollback();
          return $this->apiReturnErr($r['info']);
        }
        $msg = '优惠券发放成功，请前往百宝箱查看！';
      }
      $url = U('ExchangeLog/payback',array('uid'=>$uid,'psw'=>$psw,'id'=>$id,'info'=>$msg));
    }else{
      $url = U('ExchangeLog/pay',array('uid'=>$uid,'psw'=>$psw,'id'=>$id));
    }
    $this->model->commit();
    //前往 收货地址 + 支付/以后支付
    return $this->apiReturnSuc($url);
  }

  //初始化
  protected function _init(){
    $this -> model  = new ScoreGoodsModel();
  }

  public function detail($id){
    $entry = $this-> model->find($id);// ->cache(true)
    // dump($entry);exit;
    return $entry;
  }
  public function getPayUrl($uid,$price,$psw,$type=1){
    $now  = time();
    $code = 'S'.$now.'U'.$uid;
    $name = '订单'.$code;
    $desc = $name;
    //保留2位
    $total_price = round($price,2);
    $info = array(
      'code'=>$code,
      'name'=>$name,
      'desc'=>$desc,
      //@author 老胖子-何必都 <hebiduhebi@126.com>
      //转换成字符串，否则IOS端解析成数字类型时精度会有问题，比如74.10 被解析成74.09999999999999,从而导致APP端验证失败!
      'total_price'=>strval($total_price),
    );

    $encode = urlencode($code.$name.$desc.$total_price);
    $encode = md5(strtolower($encode));

    $info['key'] = pay_encrypt_md5($encode);
    if($type==1){
      $type= 'com.moodwo.mengwu://?type=MENGWU_ALIPAY_SCOREGOODS';
    }elseif($type==2){
      $type= 'com.moodwo.mengwu://?type=MENGWU_WXPAY_SCOREGOODS';
    }else{
      $type= 'com.moodwo.mengwu://?type=MENGWU_PAY_SCOREGOODS';
    }
    $info['show_url'] = '';//U('Webview/ExchangeLog/payBack',array('uid'=>$uid,'psw'=>$psw));
    return $this->apiReturnSuc(array('url'=>$type.'&code='.$info['code'].'&name='.$info['name'].'&desc='.$info['desc'].'&total_price='.$info['total_price'].'&key='.$info['key'].'&show_url='.$info['show_url'],'code'=>$info['code']));
  }
}